//
//  JKPdfViewController.m
//  JKPdfShow
//
//  Created by 王冲 on 2018/4/15.
//  Copyright © 2018年 希爱欧科技有限公司. All rights reserved.
//  欢迎您加入我们的iOS开发交流群  584599353

#import "JKPdfViewController.h"

#import <AFNetworking.h>
/*  下面是ppt的类*/
#import "ReaderViewController.h"
#import "ReaderConstants.h"
#import "ThumbsViewController.h"
#import "ReaderMainToolbar.h"
#import "ReaderMainPagebar.h"
#import "ReaderContentView.h"
#import "ReaderThumbCache.h"
#import "ReaderThumbQueue.h"
#import <MessageUI/MessageUI.h>
#import "ReaderDocument.h"
/*  上面是ppt的类*/

// 有关路径的类
#import "JKFilePathOperationCategory.h"

//屏幕尺寸
#define CIO_SCREEN_WIDTH  [UIScreen mainScreen].bounds.size.width
#define CIO_SCREEN_HEIGHT  [UIScreen mainScreen].bounds.size.height
/*ppt里面的类*/
#define STATUS_HEIGHT 20.0f
#define TOOLBAR_HEIGHT 44.0f
#define PAGEBAR_HEIGHT 48.0f
#define SCROLLVIEW_OUTSET_SMALL 4.0f
#define SCROLLVIEW_OUTSET_LARGE 8.0f
#define TAP_AREA_SIZE 48.0f
/***/
#define RGBCOLOR3(r,g,b,p) [UIColor colorWithRed:(r)/255.0 green:(g)/255.0 blue:(b)/255.0 alpha:p]

@interface JKPdfViewController ()<UIGestureRecognizerDelegate,MFMailComposeViewControllerDelegate,UIDocumentInteractionControllerDelegate,ReaderMainToolbarDelegate, ReaderMainPagebarDelegate, ReaderContentViewDelegate,ThumbsViewControllerDelegate,UIScrollViewDelegate>
{
    
   
    /*下面是pdf的东西*/
    NSString *courseware;
    
    ReaderDocument *document;
    UIScrollView *theScrollView;
    
    ReaderMainToolbar *mainToolbar;
    
    ReaderMainPagebar *mainPagebar;
    
    NSMutableDictionary *contentViews;
    
    UIUserInterfaceIdiom userInterfaceIdiom;
    
    NSInteger currentPage, minimumPage, maximumPage;
    
    UIDocumentInteractionController *documentInteraction;
    
    UIPrintInteractionController *printInteraction;
    
    CGFloat scrollViewOutset;
    
    CGSize lastAppearSize;
    
    NSDate *lastHideTime;
    
    BOOL ignoreDidScroll;
    
    UILabel *numberLabel;
    
    // 下一页
    UIButton *rightButton;
    // 上一页
    UIButton *leftButton;
    
    // 上下页的判断
    NSString *stringLeft;
    NSString *stringRight;
    
    /*上面是pdf的东西*/
    
    // PDF的判断
    NSString *pdfAnimationJudge;
    
    
}

@property (nonatomic, strong) ReaderDocument *object;

@end

@implementation JKPdfViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.title = @"pdf的展示";
    self.view.backgroundColor = [UIColor whiteColor];
    self.edgesForExtendedLayout = UIRectEdgeNone;
    
    UIButton *button = [[UIButton alloc]initWithFrame:CGRectMake(0, 0, 150, 50)];
    button.layer.cornerRadius = 25;
    button.clipsToBounds = YES;
    [button addTarget:self action:@selector(setPdfUI) forControlEvents:UIControlEventTouchUpInside];
    button.center = self.view.center;
    [button setBackgroundColor:[UIColor brownColor]];
    [button setTitle:@"打开pdf" forState:UIControlStateNormal];
    [self.view addSubview:button];
    
    NSString *homePath = NSHomeDirectory();
    
    NSLog(@"homePath == %@",homePath);
    
}

#pragma mark 判断没有添加过pdf而且是第一次添加pdf文件
-(void)setPdfUI{
    // https://www.tutorialspoint.com/ios/ios_tutorial.pdf
    // http://o6zsxfzm8.bkt.clouddn.com/FEA介绍.pdf
   courseware = [@"http://o6zsxfzm8.bkt.clouddn.com/FEA介绍.pdf" lastPathComponent];
    
//    NSString *documentsDirectory1 = [NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) lastObject];
    
    NSString *documentsDirectory1 = [[JKFilePathOperationCategory new]jKCreateDir:@"Documents/JKPdf"];
    NSFileManager *fileManager = [NSFileManager defaultManager];
    //courseware为文件名
    NSString *filePath = [documentsDirectory1 stringByAppendingPathComponent:courseware];
    
        if ([fileManager fileExistsAtPath:filePath]) {
           
            // 展示ppt
            [self showPpt];
            
        }else{
           
            [self downPpt];
        }
}

-(void)clickDownPpt{
    
    UIAlertController *alertController = [UIAlertController alertControllerWithTitle:@"您正在使用非WIFI网络，是否同意加载课件？" message:nil preferredStyle:UIAlertControllerStyleAlert];
    
    UIAlertAction *alertAction = [UIAlertAction actionWithTitle:@"否" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        
        NSLog(@"否");
    }];
    
    UIAlertAction *alertAction2 = [UIAlertAction actionWithTitle:@"是" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        
        NSLog(@"是");
        [self downPpt];
    }];
    
    [alertController addAction:alertAction];
    [alertController addAction:alertAction2];
    
    [self presentViewController:alertController animated:YES completion:nil];
}

#pragma mark 下载PPT
-(void)downPpt{
    
    NSLog(@"下载ppt");

    //NSString *documentsDirectory = [NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) lastObject];
    NSString *documentsDirectory = [[JKFilePathOperationCategory new]jKCreateDir:@"Documents/JKPdf"];
    
    NSString *urlString = @"http://o6zsxfzm8.bkt.clouddn.com/FEA介绍.pdf";
    urlString = [urlString  stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet URLQueryAllowedCharacterSet]];
    NSURL *url = [NSURL URLWithString:urlString];
    NSURLRequest *request = [NSURLRequest requestWithURL:url];
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    NSProgress *jkProgress = nil;
    NSURLSessionDownloadTask *downloadTask = [manager downloadTaskWithRequest:request progress:&jkProgress destination:^NSURL *(NSURL *targetPath, NSURLResponse *response) {
        
        NSString *path = [documentsDirectory stringByAppendingPathComponent:courseware];
        NSLog(@"文件路径＝＝＝%@",path);
        return [NSURL fileURLWithPath:path];
        
    } completionHandler:^(NSURLResponse *response, NSURL *filePath, NSError *error) {

        if (error == nil) {
            
            NSLog(@"下载完成");
            [self showPpt];
        }
        
    }];
    
    // 4. 开启下载任务
    [manager setDownloadTaskDidWriteDataBlock:^(NSURLSession * _Nonnull session, NSURLSessionDownloadTask * _Nonnull downloadTask, int64_t bytesWritten, int64_t totalBytesWritten, int64_t totalBytesExpectedToWrite) {
        
        float progress = (float)totalBytesWritten / totalBytesExpectedToWrite;
        int a = progress*100;
        NSLog(@"下载进度=%d%% 下载的小数progress=%f",a,progress);
      
    }];
    
    [downloadTask resume];
    
    NSLog(@"总大小：%lld,当前大小:%lld",jkProgress.totalUnitCount,jkProgress.completedUnitCount);
    
    
}

#pragma mark 展示ppt
-(void)showPpt{
    
    //NSString *documentsDirectory = [NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) lastObject];
    NSString *documentsDirectory = [[JKFilePathOperationCategory new]jKCreateDir:@"Documents/JKPdf"];
    NSString *filePath = [documentsDirectory stringByAppendingPathComponent:courseware]; //docPath为文件名
    NSString *phrase = nil;
    
    ReaderDocument *document = [ReaderDocument withDocumentFilePath:filePath password:phrase];
    
    if (document != nil)
    {
        self.object = document;
        self->document = document;
        [self setUIData:document];
    }
    else
    {
        
    }
}


#pragma mark 下面是ppt的代码
- (void)updateContentSize:(UIScrollView *)scrollView
{
    CGFloat contentHeight = scrollView.bounds.size.height; // Height
    
    CGFloat contentWidth = (scrollView.bounds.size.width * maximumPage);
    
    scrollView.contentSize = CGSizeMake(contentWidth, contentHeight);
}

- (void)updateContentViews:(UIScrollView *)scrollView
{
    [self updateContentSize:scrollView]; // Update content size first
    [contentViews enumerateKeysAndObjectsUsingBlock: // Enumerate content views
     ^(NSNumber *key, ReaderContentView *contentView, BOOL *stop)
     {
         NSInteger page = [key integerValue]; // Page number value
         // CIO_SCREEN_WIDTH-100
         CGRect viewRect = CGRectMake(0, 0, CIO_SCREEN_WIDTH, scrollView.bounds.size.height);
         //            viewRect.size = scrollView.bounds.size;
         
         viewRect.origin.x = (viewRect.size.width * (page - 1)); // Update X
         
         contentView.frame = CGRectInset(viewRect, scrollViewOutset, 0.0f);
     }
     ];
    
    NSInteger page = currentPage; // Update scroll view offset to current page
    
    CGPoint contentOffset = CGPointMake((scrollView.bounds.size.width * (page - 1)), 0.0f);
    
    if (CGPointEqualToPoint(scrollView.contentOffset, contentOffset) == false) // Update
    {
        scrollView.contentOffset = contentOffset; // Update content offset
    }
    
    [mainToolbar setBookmarkState:[document.bookmarks containsIndex:page]];
    
    [mainPagebar updatePagebar]; // Update page bar
}

- (void)addContentView:(UIScrollView *)scrollView page:(NSInteger)page
{
    // CIO_SCREEN_WIDTH-100
    CGRect viewRect = CGRectMake(0, 0, CIO_SCREEN_WIDTH, scrollView.bounds.size.height);
    //viewRect.size = scrollView.bounds.size;
    
    viewRect.origin.x = (viewRect.size.width * (page - 1));
    viewRect = CGRectInset(viewRect, scrollViewOutset, 0.0f);
    
    NSURL *fileURL = document.fileURL;
    NSString *phrase = document.password;
    NSString *guid = document.guid; // Document properties
    
    ReaderContentView *contentView = [[ReaderContentView alloc] initWithFrame:viewRect fileURL:fileURL page:page password:phrase]; // ReaderContentView
    
    contentView.message = self;
    [contentViews setObject:contentView forKey:[NSNumber numberWithInteger:page]];
    [scrollView addSubview:contentView];
    
    [contentView showPageThumb:fileURL page:page password:phrase guid:guid]; // Request page preview thumb
}

- (void)layoutContentViews:(UIScrollView *)scrollView
{
    CGFloat viewWidth = scrollView.bounds.size.width; // View width
    
    CGFloat contentOffsetX = scrollView.contentOffset.x; // Content offset X
    
    NSInteger pageB = ((contentOffsetX + viewWidth - 1.0f) / viewWidth); // Pages
    
    NSInteger pageA = (contentOffsetX / viewWidth);
    pageB += 2; // Add extra pages
    
    if (pageA < minimumPage) pageA = minimumPage;
    if (pageB > maximumPage) pageB = maximumPage;
    
    NSRange pageRange = NSMakeRange(pageA, (pageB - pageA + 1)); // Make page range (A to B)
    
    NSMutableIndexSet *pageSet = [NSMutableIndexSet indexSetWithIndexesInRange:pageRange];
    
    for (NSNumber *key in [contentViews allKeys]) // Enumerate content views
    {
        NSInteger page = [key integerValue]; // Page number value
        
        if ([pageSet containsIndex:page] == NO) // Remove content view
        {
            ReaderContentView *contentView = [contentViews objectForKey:key];
            
            [contentView removeFromSuperview]; [contentViews removeObjectForKey:key];
        }
        else // Visible content view - so remove it from page set
        {
            [pageSet removeIndex:page];
        }
    }
    
    NSInteger pages = pageSet.count;
    
    if (pages > 0) // We have pages to add
    {
        NSEnumerationOptions options = 0; // Default
        
        if (pages == 2) // Handle case of only two content views
        {
            
            if ((maximumPage > 2) && ([pageSet lastIndex] == maximumPage)) options = NSEnumerationReverse;
            
            
        }
        else if (pages == 3) // Handle three content views - show the middle one first
        {
            NSMutableIndexSet *workSet = [pageSet mutableCopy]; options = NSEnumerationReverse;
            
            [workSet removeIndex:[pageSet firstIndex]]; [workSet removeIndex:[pageSet lastIndex]];
            
            NSInteger page = [workSet firstIndex]; [pageSet removeIndex:page];
            
            [self addContentView:scrollView page:page];
        }
        
        [pageSet enumerateIndexesWithOptions:options usingBlock: // Enumerate page set
         ^(NSUInteger page, BOOL *stop)
         {
             
             [self addContentView:scrollView page:page];
             
         }
         ];
    }
}

#pragma mark 左右滑动的页码展示
- (void)handleScrollViewDidEnd:(UIScrollView *)scrollView
{
    
    CGFloat viewWidth = scrollView.bounds.size.width; // Scroll view width
    
    CGFloat contentOffsetX = scrollView.contentOffset.x; // Content offset X
    NSInteger page = (contentOffsetX / viewWidth); page++; // Page number
    
    if (page != currentPage) // Only if on different page
    {
        currentPage = page;
        document.pageNumber = [NSNumber numberWithInteger:page];
        
        [contentViews enumerateKeysAndObjectsUsingBlock: // Enumerate content views
         ^(NSNumber *key, ReaderContentView *contentView, BOOL *stop)
         {
             if ([key integerValue] != page) [contentView zoomResetAnimated:NO];
         }
         ];
        
        [mainToolbar setBookmarkState:[document.bookmarks containsIndex:page]];
        
        numberLabel.text = [NSString stringWithFormat:@"%ld/%ld",(long)page,maximumPage];
        
        NSString *stringPrevious1 = [NSString stringWithFormat:@"%ld",(long)page];
        NSString *stringPrevious2 = [NSString stringWithFormat:@"%ld",(long)maximumPage];
        
        if ([stringPrevious1 isEqualToString:@"1"]) {
            
            [leftButton setBackgroundImage:[UIImage imageNamed:@"page_last_off"] forState:UIControlStateNormal];
            stringLeft = @"1";
            
        }else{
            
            [leftButton setBackgroundImage:[UIImage imageNamed:@"page_last_on"] forState:UIControlStateNormal];
            stringLeft = @"0";
        }
        
        if ([stringPrevious1 isEqualToString:stringPrevious2]) {
            
            [rightButton setBackgroundImage:[UIImage imageNamed:@"page_next_off"] forState:UIControlStateNormal];
            stringRight = @"1";
            
        }else{
            
            [rightButton setBackgroundImage:[UIImage imageNamed:@"page_next_on"] forState:UIControlStateNormal];
            stringRight = @"0";
        }
        
        [mainPagebar updatePagebar]; // Update page bar
    }
}

- (void)showDocumentPage:(NSInteger)page
{
    if (page != currentPage) // Only if on different page
    {
        if ((page < minimumPage) || (page > maximumPage)) return;
        
        currentPage = page; document.pageNumber = [NSNumber numberWithInteger:page];
        
        CGPoint contentOffset = CGPointMake((theScrollView.bounds.size.width * (page - 1)), 0.0f);
        
        
        if (CGPointEqualToPoint(theScrollView.contentOffset, contentOffset) == true)
            [self layoutContentViews:theScrollView];
        else
            [theScrollView setContentOffset:contentOffset];
        
        [contentViews enumerateKeysAndObjectsUsingBlock: // Enumerate content views
         ^(NSNumber *key, ReaderContentView *contentView, BOOL *stop)
         {
             if ([key integerValue] != page) [contentView zoomResetAnimated:NO];
         }
         ];
        
        [mainToolbar setBookmarkState:[document.bookmarks containsIndex:page]];
        
        [mainPagebar updatePagebar]; // Update page bar
    }
    
    
}

- (void)showDocument
{
    [self updateContentSize:theScrollView]; // Update content size first
    
    [self showDocumentPage:[document.pageNumber integerValue]]; // Show page
    
    document.lastOpen = [NSDate date]; // Update document last opened date
}

- (void)closeDocument
{
    
}

- (void)viewDidUnload
{
    mainToolbar = nil; mainPagebar = nil;
    
    theScrollView = nil; contentViews = nil; lastHideTime = nil;
    
    documentInteraction = nil; printInteraction = nil;
    
    lastAppearSize = CGSizeZero;
    currentPage = 0;
    
    [super viewDidUnload];
}

- (void)willRotateToInterfaceOrientation:(UIInterfaceOrientation)toInterfaceOrientation duration:(NSTimeInterval)duration
{
    if (userInterfaceIdiom == UIUserInterfaceIdiomPad) if (printInteraction != nil) [printInteraction dismissAnimated:NO];
    
    ignoreDidScroll = YES;
}

- (void)willAnimateRotationToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation duration:(NSTimeInterval)duration
{
    if (CGSizeEqualToSize(theScrollView.contentSize, CGSizeZero) == false)
    {
        [self updateContentViews:theScrollView]; lastAppearSize = CGSizeZero;
    }
}

- (void)didRotateFromInterfaceOrientation:(UIInterfaceOrientation)fromInterfaceOrientation
{
    ignoreDidScroll = NO;
}

- (void)didReceiveMemoryWarning
{
#ifdef DEBUG
    NSLog(@"%s", __FUNCTION__);
#endif
    
    [super didReceiveMemoryWarning];
}

#pragma mark - UIScrollViewDelegate methods
- (void)scrollViewDidScroll:(UIScrollView *)scrollView
{
   if (ignoreDidScroll == NO) [self layoutContentViews:scrollView];
}

- (void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView
{
    [self handleScrollViewDidEnd:scrollView];
}

- (void)scrollViewDidEndScrollingAnimation:(UIScrollView *)scrollView
{
    pdfAnimationJudge = @"0";
    [self handleScrollViewDidEnd:scrollView];
}

#pragma mark - UIGestureRecognizerDelegate methods
- (BOOL)gestureRecognizer:(UIGestureRecognizer *)recognizer shouldReceiveTouch:(UITouch *)touch
{
    if ([touch.view isKindOfClass:[UIScrollView class]]) return YES;
    
    return NO;
}

#pragma mark 上一页ppt
- (void)decrementPageNumber
{
    if ([stringLeft isEqualToString:@"1"]) {
        
        return;
    }
    
    if ([pdfAnimationJudge isEqualToString:@"1"]) {
        
        return;
    }
    pdfAnimationJudge = @"1";
    
    if ((maximumPage > minimumPage) && (currentPage != minimumPage))
    {
        CGPoint contentOffset = theScrollView.contentOffset; // Offset
        
        contentOffset.x -= theScrollView.bounds.size.width; // View X--
        
        [theScrollView setContentOffset:contentOffset animated:YES];
        
        NSLog(@"currentPage=%ld",(long)currentPage);
        numberLabel.text = [NSString stringWithFormat:@"%ld/%ld",(long)currentPage-1,(long)maximumPage];
        
        NSString *stringPrevious1 = [NSString stringWithFormat:@"%ld",(long)currentPage+1];
        NSString *stringPrevious2 = [NSString stringWithFormat:@"%ld",(long)maximumPage];
        
        if ([stringPrevious1 isEqualToString:@"1"]) {
            
            [leftButton setBackgroundImage:[UIImage imageNamed:@"page_last_off"] forState:UIControlStateNormal];
            stringLeft = @"1";
            
        }else{
            
            [leftButton setBackgroundImage:[UIImage imageNamed:@"page_last_on"] forState:UIControlStateNormal];
            stringLeft = @"0";
        }
        
        if ([stringPrevious1 isEqualToString:stringPrevious2]) {
            
            [rightButton setBackgroundImage:[UIImage imageNamed:@"page_next_off"] forState:UIControlStateNormal];
            stringRight = @"1";
            
        }else{
            
            [rightButton setBackgroundImage:[UIImage imageNamed:@"page_next_on"] forState:UIControlStateNormal];
            stringRight = @"0";
        }
    }
}

#pragma mark 下一页ppt
- (void)incrementPageNumber
{
    if ([stringRight isEqualToString:@"1"]) {
        return;
    }
    
    if ([pdfAnimationJudge isEqualToString:@"1"]) {
        
        return;
    }
    pdfAnimationJudge = @"1";
    
    if ((maximumPage > minimumPage) && (currentPage != maximumPage))
    {
        CGPoint contentOffset = theScrollView.contentOffset; // Offset
        
        contentOffset.x += theScrollView.bounds.size.width; // View X++
        
        [theScrollView setContentOffset:contentOffset animated:YES];
        
        NSLog(@"currentPage=%ld",(long)currentPage);
        numberLabel.text = [NSString stringWithFormat:@"%ld/%ld",(long)currentPage+1,(long)maximumPage];
        
        NSString *stringNext1 = [NSString stringWithFormat:@"%ld",(long)currentPage+1];
        NSString *stringNext2 = [NSString stringWithFormat:@"%ld",(long)maximumPage];
        
        if ([stringNext1 isEqualToString:stringNext2]) {
            
            [rightButton setBackgroundImage:[UIImage imageNamed:@"page_next_off"] forState:UIControlStateNormal];
            stringRight = @"1";
            
        }else{
            
            [rightButton setBackgroundImage:[UIImage imageNamed:@"page_next_on"] forState:UIControlStateNormal];
            stringRight = @"0";
        }
        
        if ([stringNext1 isEqualToString:@"1"]) {
            
            [leftButton setBackgroundImage:[UIImage imageNamed:@"page_last_off"] forState:UIControlStateNormal];
            stringLeft = @"1";
            
        }else{
            
            [leftButton setBackgroundImage:[UIImage imageNamed:@"page_last_on"] forState:UIControlStateNormal];
            stringLeft = @"0";
        }
    }
}

#pragma mark - ReaderContentViewDelegate methods
- (void)contentView:(ReaderContentView *)contentView touchesBegan:(NSSet *)touches
{
    if ((mainToolbar.alpha > 0.0f) || (mainPagebar.alpha > 0.0f))
    {
        if (touches.count == 1) // Single touches only
        {
            UITouch *touch = [touches anyObject]; // Touch info
            
            CGPoint point = [touch locationInView:self.view]; // Touch location
            
            CGRect areaRect = CGRectInset(self.view.bounds, TAP_AREA_SIZE, TAP_AREA_SIZE);
            
            if (CGRectContainsPoint(areaRect, point) == false) return;
        }
        
        [mainToolbar hideToolbar]; [mainPagebar hidePagebar]; // Hide
        
        lastHideTime = [NSDate date]; // Set last hide time
    }
}

#pragma mark - ReaderMainToolbarDelegate methods
- (void)tappedInToolbar:(ReaderMainToolbar *)toolbar doneButton:(UIButton *)button
{
#if (READER_STANDALONE == FALSE) // Option
    
    [self closeDocument]; // Close ReaderViewController
    
#endif // end of READER_STANDALONE Option
}

- (void)tappedInToolbar:(ReaderMainToolbar *)toolbar thumbsButton:(UIButton *)button
{
#if (READER_ENABLE_THUMBS == TRUE) // Option
    
    if (printInteraction != nil) [printInteraction dismissAnimated:NO];
    
    ThumbsViewController *thumbsViewController = [[ThumbsViewController alloc] initWithReaderDocument:document];
    
    thumbsViewController.title = self.title; thumbsViewController.delegate = self; // ThumbsViewControllerDelegate
    
    thumbsViewController.modalTransitionStyle = UIModalTransitionStyleCrossDissolve;
    thumbsViewController.modalPresentationStyle = UIModalPresentationFullScreen;
    
    [self presentViewController:thumbsViewController animated:NO completion:NULL];
    
#endif // end of READER_ENABLE_THUMBS Option
}
- (void)tappedInToolbar:(ReaderMainToolbar *)toolbar exportButton:(UIButton *)button
{
    if (printInteraction != nil) [printInteraction dismissAnimated:YES];
    
    NSURL *fileURL = document.fileURL; // Document file URL
    
    documentInteraction = [UIDocumentInteractionController interactionControllerWithURL:fileURL];
    
    documentInteraction.delegate = self; // UIDocumentInteractionControllerDelegate
    
    [documentInteraction presentOpenInMenuFromRect:button.bounds inView:button animated:YES];
}

- (void)tappedInToolbar:(ReaderMainToolbar *)toolbar printButton:(UIButton *)button
{
    if ([UIPrintInteractionController isPrintingAvailable] == YES)
    {
        NSURL *fileURL = document.fileURL; // Document file URL
        
        if ([UIPrintInteractionController canPrintURL:fileURL] == YES)
        {
            printInteraction = [UIPrintInteractionController sharedPrintController];
            
            UIPrintInfo *printInfo = [UIPrintInfo printInfo];
            printInfo.duplex = UIPrintInfoDuplexLongEdge;
            printInfo.outputType = UIPrintInfoOutputGeneral;
            printInfo.jobName = document.fileName;
            
            printInteraction.printInfo = printInfo;
            printInteraction.printingItem = fileURL;
            printInteraction.showsPageRange = YES;
            
            if (userInterfaceIdiom == UIUserInterfaceIdiomPad) // Large device printing
            {
                [printInteraction presentFromRect:button.bounds inView:button animated:YES completionHandler:
                 ^(UIPrintInteractionController *pic, BOOL completed, NSError *error)
                 {
#ifdef DEBUG
                     if ((completed == NO) && (error != nil)) NSLog(@"%s %@", __FUNCTION__, error);
#endif
                 }
                 ];
            }
            else // Handle printing on small device
            {
                [printInteraction presentAnimated:YES completionHandler:
                 ^(UIPrintInteractionController *pic, BOOL completed, NSError *error)
                 {
#ifdef DEBUG
                     if ((completed == NO) && (error != nil)) NSLog(@"%s %@", __FUNCTION__, error);
#endif
                 }
                 ];
            }
        }
    }
}

- (void)tappedInToolbar:(ReaderMainToolbar *)toolbar emailButton:(UIButton *)button
{
    if ([MFMailComposeViewController canSendMail] == NO) return;
    
    if (printInteraction != nil) [printInteraction dismissAnimated:YES];
    
    unsigned long long fileSize = [document.fileSize unsignedLongLongValue];
    
    if (fileSize < 15728640ull) // Check attachment size limit (15MB)
    {
        NSURL *fileURL = document.fileURL; NSString *fileName = document.fileName;
        
        NSData *attachment = [NSData dataWithContentsOfURL:fileURL options:(NSDataReadingMapped|NSDataReadingUncached) error:nil];
        
        if (attachment != nil) // Ensure that we have valid document file attachment data available
        {
            MFMailComposeViewController *mailComposer = [MFMailComposeViewController new];
            
            [mailComposer addAttachmentData:attachment mimeType:@"application/pdf" fileName:fileName];
            
            [mailComposer setSubject:fileName]; // Use the document file name for the subject
            
            mailComposer.modalTransitionStyle = UIModalTransitionStyleCoverVertical;
            mailComposer.modalPresentationStyle = UIModalPresentationFormSheet;
            
            mailComposer.mailComposeDelegate = self; // MFMailComposeViewControllerDelegate
            
            [self presentViewController:mailComposer animated:YES completion:NULL];
        }
    }
}

- (void)tappedInToolbar:(ReaderMainToolbar *)toolbar markButton:(UIButton *)button
{
#if (READER_BOOKMARKS == TRUE) // Option
    
    if (printInteraction != nil) [printInteraction dismissAnimated:YES];
    
    if ([document.bookmarks containsIndex:currentPage]) // Remove bookmark
    {
        [document.bookmarks removeIndex:currentPage]; [mainToolbar setBookmarkState:NO];
    }
    else // Add the bookmarked page number to the bookmark index set
    {
        [document.bookmarks addIndex:currentPage]; [mainToolbar setBookmarkState:YES];
    }
    
#endif // end of READER_BOOKMARKS Option
}

#pragma mark - MFMailComposeViewControllerDelegate methods
- (void)mailComposeController:(MFMailComposeViewController *)controller didFinishWithResult:(MFMailComposeResult)result error:(NSError *)error
{
#ifdef DEBUG
    if ((result == MFMailComposeResultFailed) && (error != NULL)) NSLog(@"%@", error);
#endif
    
    [self dismissViewControllerAnimated:YES completion:NULL];
}

#pragma mark - UIDocumentInteractionControllerDelegate methods
- (void)documentInteractionControllerDidDismissOpenInMenu:(UIDocumentInteractionController *)controller
{
    documentInteraction = nil;
}

#pragma mark - ThumbsViewControllerDelegate methods

- (void)thumbsViewController:(ThumbsViewController *)viewController gotoPage:(NSInteger)page
{
#if (READER_ENABLE_THUMBS == TRUE) // Option
    
    [self showDocumentPage:page];
    
#endif // end of READER_ENABLE_THUMBS Option
}

- (void)dismissThumbsViewController:(ThumbsViewController *)viewController
{
#if (READER_ENABLE_THUMBS == TRUE) // Option
    
    [self dismissViewControllerAnimated:NO completion:NULL];
    
#endif // end of READER_ENABLE_THUMBS Option
}

#pragma mark - ReaderMainPagebarDelegate methods
- (void)pagebar:(ReaderMainPagebar *)pagebar gotoPage:(NSInteger)page
{
    [self showDocumentPage:page];
}

#pragma mark JK 打开指定第几页
-(void)showPage:(NSInteger)page{
    
    [self showDocumentPage:page];
    NSLog(@"currentPage=%ld",(long)currentPage);
    numberLabel.text = [NSString stringWithFormat:@"%ld/%ld",(long)page,(long)maximumPage];
}

#pragma mark 显示PDF
-(void)setUIData:(ReaderDocument *)document{
    
    UIView *pdfBackView = [[UIView alloc]initWithFrame:CGRectMake(0,50, CIO_SCREEN_WIDTH, 156)];
    [self.view addSubview:pdfBackView];
    
    assert(document != nil);          // CIO_SCREEN_WIDTH-100
    CGRect viewRect = CGRectMake(0,0, CIO_SCREEN_WIDTH, 156);
    theScrollView = [[UIScrollView alloc] initWithFrame:viewRect];
    theScrollView.showsHorizontalScrollIndicator = NO;
    theScrollView.showsVerticalScrollIndicator = NO;
    theScrollView.pagingEnabled = YES;
    // [UIColor redColor]
    theScrollView.backgroundColor = RGBCOLOR3(37, 37, 37, 1);;
    theScrollView.userInteractionEnabled = YES;
    theScrollView.delegate = self;
    [pdfBackView addSubview:theScrollView];
    
    UITapGestureRecognizer *singleTapOne = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(handleSingleTap:)];
    singleTapOne.numberOfTouchesRequired = 1; singleTapOne.numberOfTapsRequired = 1; singleTapOne.delegate = self;
    [theScrollView addGestureRecognizer:singleTapOne];
    
    contentViews = [NSMutableDictionary new];
    lastHideTime = [NSDate date];
    
    minimumPage = 1;
    maximumPage = [document.pageCount integerValue];
    
    leftButton = [[UIButton alloc]initWithFrame:CGRectMake(8,54, 24, 48)];
    [leftButton addTarget:self action:@selector(decrementPageNumber) forControlEvents:UIControlEventTouchUpInside];
    [leftButton setBackgroundImage:[UIImage imageNamed:@"page_last_off"] forState:UIControlStateNormal];
    [pdfBackView addSubview:leftButton];
    
    rightButton = [[UIButton alloc]initWithFrame:CGRectMake(CIO_SCREEN_WIDTH-8-24,54, 24, 48)];
    [rightButton addTarget:self action:@selector(incrementPageNumber) forControlEvents:UIControlEventTouchUpInside];
    //[rightButton setBackgroundColor:[UIColor greenColor]];
    [rightButton setBackgroundImage:[UIImage imageNamed:@"page_next_on"] forState:UIControlStateNormal];
    //[rightButton setTitle:@"下一页" forState:UIControlStateNormal];
    [pdfBackView addSubview:rightButton];
    
    stringLeft = @"1";
    stringRight = @"0";
    
    UIButton *downButton = [[UIButton alloc]initWithFrame:CGRectMake(50, CGRectGetMaxY(leftButton.frame)+50, 50, 50)];
    //[downButton addTarget:self action:@selector(showPage) forControlEvents:UIControlEventTouchUpInside];
    [downButton setBackgroundColor:[UIColor greenColor]];
    //[self.view addSubview:downButton];
    
    numberLabel = [[UILabel alloc]initWithFrame:CGRectMake(CIO_SCREEN_WIDTH-40-32, 128, 40, 20)];
    numberLabel.textColor = [UIColor whiteColor];
    numberLabel.backgroundColor = RGBCOLOR3(0, 0, 0, 0.64);
    numberLabel.font = [UIFont systemFontOfSize:10.f];
    numberLabel.layer.cornerRadius = 4;
    numberLabel.clipsToBounds = YES;
    numberLabel.textAlignment = NSTextAlignmentCenter;
    numberLabel.text = [NSString stringWithFormat:@"%ld/%ld",(long)minimumPage,(long)maximumPage];
    [pdfBackView addSubview:numberLabel];
    
    UIButton *showScreen = [[UIButton alloc]initWithFrame:CGRectMake(CIO_SCREEN_WIDTH-8-20, 128, 20, 20)];
    [showScreen addTarget:self action:@selector(showScreenClick) forControlEvents:UIControlEventTouchUpInside];
    [showScreen setBackgroundColor:RGBCOLOR3(0, 0, 0, 0.64)];
    [showScreen setImage:[UIImage imageNamed:@"lecture_screen"] forState:UIControlStateNormal];
    showScreen.layer.cornerRadius = 4;
    showScreen.clipsToBounds = YES;
    [pdfBackView addSubview:showScreen];
    
    [self showDocumentPage:minimumPage];
    [self updateContentViews:theScrollView];
    
    [self showPage:2];
    [self showPage:1];
    
}

#pragma mark 全屏
-(void)showScreenClick{
    
    [self handleSingleTap:nil];
}

#pragma mark 单击某一个图片
- (void)handleSingleTap:(UITapGestureRecognizer *)recognizer
{
    NSLog(@"点击的第几%ld页",(long)currentPage);
    
    ReaderViewController *readerViewController = [[ReaderViewController alloc] initWithReaderDocument:self.object];
    __weak typeof(self) weakSelf = self;
    readerViewController.pageBlock = ^(NSInteger page) {
        
        [weakSelf showPage:page];
    };
    
    //[self.navigationController pushViewController:readerViewController animated:YES];
    readerViewController.modalTransitionStyle = UIModalTransitionStyleCrossDissolve;
    //readerViewController.modalPresentationStyle = UIModalPresentationNone;
    /*
     从下往上出来
     
     UIModalPresentationOverFullScreen
     两头出来
     UIModalPresentationPageSheet
     UIModalPresentationFormSheet
     UIModalPresentationCurrentContext
     UIModalPresentationCustom
     */
    [self presentViewController:readerViewController animated:YES completion:NULL];
}




@end
